/*
 * Copyright 2010-2011 ESunny.com All right reserved. This software is the confidential and proprietary information of
 * ESunny.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with ESunny.com.
 */
package com.xjt.query.action.json;

import java.io.IOException;
import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.xjt.common.VelocityHelper;
import com.xjt.query.entity.RetModel;

/**
 * Offer JOSN 接口基础action
 * 
 * @author Jet Xu 2011-7-29 上午10:01:28
 */
public class JosnBaseAction extends ActionSupport {

    private static final Log      log              = LogFactory.getLog(JosnBaseAction.class);

    /** 序列号 */
    private static final long     serialVersionUID = 8515864970907136986L;

    /** 过滤特殊字符 */
    private static VelocityHelper helper           = new VelocityHelper();

    /**
     * 获得返回的JSON信息
     * 
     * @param data 信息列表
     * @return 返回的JSON信息
     */
    protected RetModel getReturnModel(List<?> data) {
        RetModel model = new RetModel();
        model.setResult(RetModel.RETURN_JSON_SUCCESS);
        model.setData(data);
        model.setNum(null == data ? "0" : String.valueOf(data.size()));
        return model;
    }

    /**
     * 获得返回的JSON信息
     * 
     * @author zhouhj 2011-08-02 11:21
     * @param data 信息列表
     * @param result 1表示成功，0表示失败
     * @param message 出错信息
     * @return 返回的JSON信息
     */
    protected RetModel getReturnModel(List<?> data, String result, String message) {
        RetModel model = new RetModel();
        model.setResult(result);
        model.setData(data);
        model.setNum(null == data ? "0" : String.valueOf(data.size()));
        model.setMessage(message);
        return model;
    }

    /**
     * 获得返回的JSON信息,重载上面的方法
     * 
     * @param data 数据，兼容List、Set等集合类型
     * @param result 1表示成功，0表示失败
     * @param message 出错信息
     * @return 返回的JSON信息
     */
    protected RetModel getReturnModel(Object data, String result, String message, int size) {
        RetModel model = new RetModel();
        model.setResult(result);
        model.setData(data);
        model.setNum(String.valueOf(size));
        model.setMessage(message);
        return model;
    }

    /**
     * 获取返回的信息。支持var和callback参数。
     * 
     * @param data 数据
     * @return 返回的信息
     */
    protected String getReturnString(Object data) {
        JSON json = JSONSerializer.toJSON(data);
        String varName = helper.sjs(ServletActionContext.getRequest().getParameter("var"));
        String functionName = helper.sjs(ServletActionContext.getRequest().getParameter("callback"));
        StringBuilder sBuilder = new StringBuilder();

        // 如果存在参数var
        if (null != varName && varName.trim().length() > 0) {
            sBuilder.append("var ");
            sBuilder.append(varName);
            sBuilder.append(" = ");
            sBuilder.append(json.toString());
        }
        // 如果存在参数callback
        else if (null != functionName && functionName.trim().length() > 0) {
            sBuilder.append(functionName);
            sBuilder.append("(");
            sBuilder.append(json.toString());
            sBuilder.append(")");
        } else {
            sBuilder.append(json.toString());
        }
        return sBuilder.toString();
    }

    /**
     * 输出
     * 
     * @param obj
     * @param flash 是否立即提交
     */
    protected void write(Object obj, boolean flash) {
        try {
            ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
            ServletActionContext.getResponse().getWriter().print(obj);
            if (flash) {
                ServletActionContext.getResponse().getWriter().flush();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 输出
     */
    protected void write(Object obj) {
        this.write(obj, false);
    }
}
